<template>
  <div>
    <el-form @submit.native.prevent class="query-table-form" :inline="true" :model="params">
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="借款人/担保客户查询"
          clearable
          @change="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <select-address
          v-model="params.address_code"
          :auto-top="1"
          placeholder="地址查询"
          clearable
          @change="getData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.bank_name"
          placeholder="银行名称查询"
          clearable
          @keyup.enter.native="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
    </el-form>
    <c-table
      border
      height="70vh"
      class="table-sm"
      ref="multipleTable"
      name="table"
      v-loading="loading"
      :columns="tableColumns"
      :row-key="getRowKeys"
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <template v-slot:address="scope">
        <div class="text-truncate" :title="scope.row.address">{{ scope.row.address }}</div>
      </template>
    </c-table>

    <div class="text-center mt-2">
      <el-button
        @click="onSbmit"
        :disabled="!selectData.length"
        :type="buttonType"
        :loading="submitLoading"
        class="btn-long"
      >
        {{ buttonText }}
      </el-button>
      <el-button @click="handleClose" class="btn-long">取消</el-button>
    </div>

    <el-dialog
      :visible.sync="replaceVisible"
      title="替换项目"
      top="30px"
      width="1100px"
      class="dialog-sm"
      append-to-body
      :close-on-click-modal="false"
    >
      <h5 class="text-center">已选项目</h5>

      <c-table
        :data="selectData"
        border
        class="table-sm mb-5"
        show-summary
        :summary-method="getSummaries"
        :columns="selectColumns"
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <div class="d-flex">
              <div class="d-flex flex-1">
                <div class="table-label">年收入：</div>
                {{ props.row.sale_income || '-' }} 万元
              </div>
              <div class="d-flex flex-1">
                <div class="table-label">总资产：</div>
                {{ props.row.assets_total || '-' }} 万元
              </div>
            </div>
            <div class="d-flex">
              <div class="d-flex flex-1">
                <div class="table-label">担保方式：</div>
                {{ props.row.warranty_method }}
              </div>
              <div class="d-flex flex-1">
                <div class="table-label">贷款利率：</div>
                {{ props.row.load_rate }} %
              </div>
            </div>
            <div class="d-flex">
              <div class="d-flex flex-1">
                <div class="table-label">是否为扶贫项目：</div>
                {{ enumDispute[props.row.is_poverty_project] }}
              </div>
              <div class="d-flex flex-1">
                <div class="table-label">是否购买农业保险：</div>
                {{ enumDispute[props.row.is_buy_insurance] }}
              </div>
            </div>
            <div class="d-flex">
              <div class="d-flex flex-1">
                <div class="table-label">逾期次数：</div>
                {{ props.row.overdue_count || '-' }} 次
              </div>
              <div class="d-flex flex-1">
                <div class="table-label">逾期合计金额：</div>
                {{ props.row.overdue_funds || '-' }} 万元
              </div>
            </div>
            <div class="d-flex">
              <div class="d-flex flex-1">
                <div class="table-label">联系人：</div>
                {{ props.row.corp_name }}
              </div>
              <div class="d-flex flex-1">
                <div class="table-label">联系电话：</div>
                {{ props.row.corp_phone }}
              </div>
            </div>
            <div class="d-flex">
              <div class="d-flex flex-1">
                <div class="table-label">客户住址/经营地址：</div>
                {{ props.row.address }}
              </div>
              <div class="d-flex flex-1">
                <div class="table-label">保证合同号：</div>
                {{ props.row.gua_contract }}
              </div>
            </div>
            <div class="d-flex">
              <div class="d-flex">
                <div class="table-label">备注：</div>
                {{ props.row.remark }}
              </div>
            </div>
          </template>
        </el-table-column>
        <template v-slot:use="scope">
          <div class="text-truncate" :title="scope.row.funds_use_dir">
            {{ scope.row.funds_use_dir }}
          </div>
        </template>

        <template v-slot:mainBudiness="scope">
          <div class="text-truncate" :title="scope.row.main_business_bank">
            {{ scope.row.main_business_bank }}
          </div>
        </template>
      </c-table>

      <h5 class="text-center">
        替换项目
        <el-button type="primary" icon="el-icon-upload2" @click="showImportVisible" class="ml-5">
          导入
        </el-button>
      </h5>
      <c-table
        :data="editData"
        border
        class="table-sm"
        show-summary
        :summary-method="getSummaries"
        :columns="editColumns"
      >
        <template v-slot:use="scope">
          <div class="text-truncate" :title="scope.row.funds_use_dir">
            {{ scope.row.funds_use_dir }}
          </div>
        </template>

        <template v-slot:mainBudiness="scope">
          <div class="text-truncate" :title="scope.row.main_business_bank">
            {{ scope.row.main_business_bank }}
          </div>
        </template>
      </c-table>
      <span class="text-sm">备注： 替换的项目需要与选择的项目数量一致，并保证贷款金额合计相等</span>

      <div class="text-center mt-5">
        <el-button @click="onReplaceData" type="primary" class="btn-long">完成</el-button>
        <el-button @click="closeReplace" class="btn-long">取消</el-button>
      </div>

      <project-new-dialog
        :visible.sync="formVisible"
        :isBackData="true"
        :table-id="tableId"
        :form-data="formData"
        @back="setEditRow"
      ></project-new-dialog>

      <import-excel
        excel-template="/static/files/一县一业产业贷导入模板.xlsx"
        :row="3"
        :column="1"
        :options="importOption"
        title="导入项目信息"
        @success="importSuccess"
        :visible.sync="importVisible"
      ></import-excel>
    </el-dialog>
  </div>
</template>

<script>
import SelectAddress from '@/components/select/SelectAddress'
import ProjectNewDialog, { enumCustomType } from '@/bank/views/hnd/ProjectNewDialog'
import { enumDispute } from '@/bank/plugins/enum'
import { add } from '@vimi/utils-tool'
import { mapGetters } from 'vuex'
import ImportExcel from '@/bank/views/hnd/ImportExcel'
import { dateFormat } from '@/common/utils/common'
export default {
  components: {
    SelectAddress,
    ProjectNewDialog,
    ImportExcel,
  },
  props: {
    type: {
      type: String,
      default: '1',
    },
  },
  data() {
    const columns = [
      { attrs: { label: '序号', type: 'index', align: 'center', minWidth: 30 } },
      { attrs: { label: '借款人/担保客户', prop: 'customer_name', minWidth: '120px' } },
      {
        attrs: {
          label: '行业类型',
          prop: 'main_business_bank',
          align: 'center',
          minWidth: '110px',
        },
        slot: 'mainBudiness',
      },
      {
        attrs: {
          label: '客户身份证号码/统一社会信用代码',
          prop: 'lender_idcard',
          minWidth: '120px',
        },
      },
      { attrs: { label: '客户类型', prop: 'org_class' }, process: v => enumCustomType[v] },
      { attrs: { label: '贷款金额/拟担保金额(万元)', prop: 'warranty_amount', minWidth: '120px' } },
      {
        attrs: { label: '放款日/拟担保起始日', prop: 'load_date', align: 'center' },
        process: v => this.$utils.dateFormat(v, 'yyyy-MM-dd'),
      },
      {
        attrs: { label: '到期日', prop: 'load_end_date', align: 'center' },
        process: v => this.$utils.dateFormat(v, 'yyyy-MM-dd'),
      },
      { attrs: { label: '贷款期限', prop: 'warranty_period', align: 'center' } },
      { attrs: { label: '借款用途', prop: 'funds_use_dir', align: 'center' }, slot: 'use' },
    ]
    return {
      enumDispute,
      enumCustomType,
      loading: false,
      submitLoading: false,
      params: {
        'import_status.eq': '1',
        'update_apply.eq': 0,
      },
      tableName: 'datum_one_county_industry',
      tableColumns: [
        { attrs: { label: '选择', type: 'selection', align: 'center', reserveSelection: true } },
        { attrs: { label: '借款人/担保客户', prop: 'customer_name', minWidth: '120px' } },
        { attrs: { label: '地址', prop: 'address' }, slot: 'address' },
        { attrs: { label: '联系电话', prop: 'corp_phone', align: 'center' } },
        { attrs: { label: '导入银行', prop: 'bank_name', align: 'center' } },
        { attrs: { label: '放款日/拟担保起始日', prop: 'loadDate', align: 'center' } },
        { attrs: { label: '到期日', prop: 'loadEndDate', align: 'center' } },
        { attrs: { label: '贷款期限', prop: 'warranty_period', align: 'center' } },
        { attrs: { label: '贷款金额/拟担保金额(万元)', prop: 'warranty_amount', align: 'center' } },
      ],
      selectColumns: columns,
      editColumns: [
        ...columns,
        {
          attrs: { label: '操作', align: 'center', width: '60px' },
          operations: [{ content: '编辑', icon: 'fa fa-edit', event: this.editRow }],
        },
      ],
      tableData: [],

      selectData: [],
      selectFundsCount: 0,
      editData: [],
      replaceVisible: false,
      tableId: '',
      formData: {},
      formVisible: false,
      editIndex: '',
      importVisible: false,
      banks: '',
      importOption: {
        B: { k: 'customer_name' },
        C: { k: 'org_class_name' },
        D: { k: 'main_business_bank' },
        E: { k: 'sale_income' },
        F: { k: 'assets_total' },
        G: { k: 'warranty_amount' },
        H: { k: 'load_date', t: 'd', f: v => dateFormat(v, 'yyyy/M/d') },
        I: { k: 'load_end_date', t: 'd', f: v => dateFormat(v, 'yyyy/M/d') },
        J: { k: 'warranty_period' },
        K: { k: 'load_rate' },
        L: { k: 'warranty_method' },
        M: { k: 'is_buy_insurance' },
        N: { k: 'funds_use_dir' },
        O: { k: 'is_poverty_project' },
        P: { k: 'overdue_count' },
        Q: { k: 'overdue_funds' },
        R: { k: 'corp_name' },
        S: { k: 'corp_phone' },
        T: { k: 'lender_idcard' },
        U: { k: 'address_detail' },
        V: { k: 'remark' },
      },
    }
  },
  computed: {
    ...mapGetters(['user', 'clientId', 'org']),
    isDelete() {
      return +this.type === 2
    },
    buttonType() {
      return this.isDelete ? 'danger' : 'primary'
    },
    buttonText() {
      return this.isDelete ? '删除' : '替换'
    },
  },
  created() {
    this.$store.dispatch('getAccessData')
    this.params['bank_code.endlike'] = this.org.orgCode
    this.getData()
  },
  methods: {
    importSuccess(data) {
      const length = this.selectData.length
      this.editData = data.slice(0, length)
    },
    showImportVisible() {
      this.importVisible = true
    },
    fetchData(params) {
      return this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, this.order || {})
      )
    },
    async getData() {
      this.loading = true
      const [res = {}] = await this.fetchData(this.params)
      this.loading = false

      const data = (res && res.data) || []
      this.tableData = data.map(this.dataAdapter)
    },
    onReplaceData() {
      let funds = 0
      for (let p of this.editData) {
        if (!p.customer_name) {
          return this.$message.warning('请完善替换的项目信息')
        }
        funds = add(funds, p.warranty_amount)
      }
      if (this.selectFundsCount !== funds) {
        return this.$message.warning('项目金额总和不等于需要替换项目的金额总和')
      }
      // console.log(this.selectFundsCount)
    },
    editRow(row) {
      this.editIndex = row.index || 0
      this.formData = row ? { ...row } : {}
      this.formVisible = true
    },
    setEditRow(data) {
      this.$set(this.editData, this.editIndex, { ...data })
    },
    dataAdapter(item) {
      item.loadDate = this.$utils.dateFormat(item.load_date, 'yyyy-MM-dd')
      item.loadEndDate = this.$utils.dateFormat(item.load_end_date, 'yyyy-MM-dd')

      return item
    },
    getRowKeys(row) {
      return row.customer_related_id
    },
    handleSelectionChange(select) {
      this.selectData = select
    },
    slaveData(data) {
      return data.map(item => {
        const {
          update_apply: update,
          create_time: create,
          submit_person: submit,
          loadDate,
          loadEndDate,
          ...newItem
        } = { ...item }
        if (!this.banks.includes(item.bank_id)) {
          this.banks.push(item.bank_id)
        }
        const obj = {}
        Object.keys(newItem).forEach(key => {
          if (newItem[key]) {
            obj[key] = newItem[key]
          }
        })
        obj.update_apply = this.type
        return obj
      })
    },
    onSbmit() {
      this.selectFundsCount = 0
      this.banks = []
      this.editData = []
      if (!this.isDelete) {
        this.selectData.forEach((item, index) => {
          this.selectFundsCount = add(this.selectFundsCount, item.warranty_amount)
          this.editData.push({ index })
        })
        this.replaceVisible = true
      } else {
        const data = this.slaveData(this.selectData)

        const masterData = {
          project_count: this.selectData.length,
          bank_id: this.clientId,
          bank_name: this.org.orgName,
          bank_code: this.org.orgCode,
          bank_count: this.banks.length,
          update_approval_type: 2,
        }

        const formData = {
          masterTableInfo: JSON.stringify(masterData),
          masterTableName: 'update_approval_batch',
          slaveTableInfo: JSON.stringify(data),
          slaveTableName: 'update_approval_batch_detail',
        }

        this.$utils
          .msgbox({
            message: `确定申请删除已选的${this.selectData.length}个客户?`,
            beforeClose: () => this.$api.relatedBatch(this.$serviceName, formData),
          })
          .then(() => {
            this.$message.success('已申请，请等待担保公司审核！')
            this.getData()
            this.$emit('success', true)
            this.handleClose()
          })
          .catch(() => this.$message.error('申请失败，请重试！'))
      }
    },
    clearAll() {
      this.selectData = []
      const $tableRef = this.$refs.multipleTable.$refs.table
      $tableRef.clearSelection()
    },
    handleClose() {
      this.clearAll()
      this.$emit('close', true)
    },
    closeReplace() {
      this.replaceVisible = false
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (column.property === 'warranty_amount') {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += '万元'
          } else {
            sums[index] = '-'
          }
        } else {
          sums[index] = '-'
        }
      })
      return sums
    },
  },
}
</script>
<style lang="scss" scoped>
.table-label {
  text-align: left;
  width: 140px;
  color: #99a9bf;
}
</style>
